<template>
    <nut-form>
        <!-- 车牌号 -->
        <nut-form-item label-position="top" label="车牌">
            <LicensePlateInput
                v-model="licensePlateValue"
                ref="licensePlateInputRef"
                @focus="handleInputFocus"
            />
        </nut-form-item>

        <!-- 出行时间 -->
        <template v-if="pageType === 'add' || pageType === 'edit'">
            <nut-cell
                title="出行时间"
                :desc="String(dateTimeShowValue)"
                @click="show = true"
            ></nut-cell>
            <nut-popup v-model:visible="show" position="bottom" round :style="{ height: '50%' }">
                <nut-date-picker
                    type="hour-minute"
                    v-model="dateTimeInitialValue"
                    :is-show-chinese="true"
                    :three-dimensional="false"
                    @confirm="confirm"
                ></nut-date-picker>
            </nut-popup>

            <!-- 联系电话 -->
            <!-- <nut-cell title="联系电话" center>
                <template #desc>
                    <nut-input
                        v-model="phoneNumberValue"
                        placeholder="请输入联系电话"
                        type="number"
                        input-align="right"
                        :border="false"
                    />
                </template>
            </nut-cell> -->
        </template>
    </nut-form>

    <!-- <view v-if="pageType === 'add'" class="flex items-center mt-4 pl-4">
        <nut-checkbox v-model="isAgreeValue"></nut-checkbox>
        <view class="flex items-center flex-wrap">
            <span class="text-sm text-gray-500">我已阅读并同意</span>
            <span class="text-sm text-blue-500" @click="toAgreement('user')">《用户服务协议》</span>
            <span class="text-sm text-gray-500">及</span>
            <span class="text-sm text-blue-500" @click="toAgreement('privacy')">《隐私政策》</span>
            <span class="text-sm text-gray-500">并同意按隐私政策处理我的敏感个人信息</span>
        </view>
    </view> -->

    <view class="flex justify-center mt-8">
        <!-- <nut-button type="default">拍照识车牌</nut-button> -->
        <template v-if="pageType === 'add'">
            <nut-button type="primary" @click="hanldeBtnClick('create')">创建车辆信息</nut-button>
        </template>
        <template v-else-if="pageType === 'edit'">
            <nut-button type="primary" @click="hanldeBtnClick('update')">更新车辆信息</nut-button>
        </template>
        <template v-else>
            <nut-button type="primary" @click="hanldeBtnClick('query')">查询车辆信息</nut-button>
        </template>
    </view>

    <!-- 出行时间 -->
    <template v-if="pageType === 'query' && queryLicenseInfo">
        <nut-cell-group title="为您查到的信息如下">
            <nut-cell title="车牌号" :desc="queryLicenseInfo?.license"></nut-cell>
            <nut-cell title="出行时间" :desc="queryLicenseInfo?.time"></nut-cell>
            <!-- <nut-cell title="联系电话" :desc="queryLicenseInfo?.phoneNumber">
                <template #desc>
                    <div class="flex justify-end items-center">
                        <span class="mr-2 text-sm">{{ queryLicenseInfo?.phoneNumber }}</span>
                        <nut-button type="primary" size="mini" @click="copyPhoneNumber">
                            复制
                        </nut-button>
                    </div>
                </template>
            </nut-cell> -->
        </nut-cell-group>
    </template>

    <LicensePlateKeyboard
        v-if="isShowKeyboard"
        @keyClick="handleKeyboardClick"
        @delete="handleKeyboardDelete"
        @confirm="handleKeyboardConfirm"
        :keyboardMode="currentKeyboardMode"
    />
</template>

<script lang="ts" setup>
import Taro from '@tarojs/taro'
import { ref, computed, onMounted } from 'vue'
import LicensePlateInput from '../../components/LicensePlateInput.vue'
import LicensePlateKeyboard from '../../components/LicensePlateKeyboard.vue'
import { licenseRecordCreate, licenseRecordQuery, licenseRecordUpdate } from '@/api/license'
import { ILicenseRecord } from '@/config/interface'
import { useShareApp } from '@/utils/share'
useShareApp()
import { useAuth } from '@/config/auth'
const { isLogin, toLogin } = useAuth()

// useRouter 钩子
import { useRouter } from '@tarojs/taro'
const router = useRouter()
const { pageType, license } = router.params

// 1.车牌
const licensePlateValue = ref('')
const licensePlateInputRef = ref<InstanceType<typeof LicensePlateInput> | null>(null)
const currentInputIndex = ref(0)
const showKeyboardFlag = ref(true)
const isShowKeyboard = computed(() => {
    return showKeyboardFlag.value && pageType !== 'edit'
})

const currentKeyboardMode = computed(() => {
    return currentInputIndex.value === 0 ? 'province' : 'number'
})

const handleInputFocus = (index) => {
    currentInputIndex.value = index
    showKeyboardFlag.value = true
}

const handleKeyboardClick = (key) => {
    licensePlateInputRef.value?.setInputValue(key)
}

const handleKeyboardDelete = () => {
    licensePlateInputRef.value?.deleteInputValue()
}

const handleKeyboardConfirm = () => {
    showKeyboardFlag.value = false
    licensePlateInputRef.value?.blur()
    currentInputIndex.value = -1
}

// 2.时间选择
const show = ref(false)
const dateTimeShowValue = ref('07:00')
const dateTimeInitialValue = ref(new Date(2025, 1, 1, 7, 0))
const confirm = ({ selectedValue }) => {
    dateTimeShowValue.value = `${selectedValue[0]}:${selectedValue[1]}`
    show.value = false
}

// 3.联系电话
const phoneNumberValue = ref('')

// const isAgreeValue = ref(false)
// const toAgreement = (agreementType: string) => {
//     Taro.navigateTo({
//         url: `/pages/agreement/index?agreementType=${agreementType}`
//     })
// }

// 4.创建车辆信息
const createLicenseRecord = async () => {
    try {
        if (!licensePlateValue.value) {
            Taro.showToast({
                title: '请补充车牌',
                icon: 'none'
            })
            return
        }
        if (!dateTimeShowValue.value) {
            Taro.showToast({
                title: '请补充时间',
                icon: 'none'
            })
            return
        }
        // if (!phoneNumberValue.value) {
        //     Taro.showToast({
        //         title: '请补充联系方式',
        //         icon: 'none'
        //     })
        //     return
        // }
        const { result } = await licenseRecordCreate({
            license: licensePlateValue.value,
            time: dateTimeShowValue.value,
            phoneNumber: phoneNumberValue.value
        })
        console.log('result', result)

        Taro.showToast({
            title: '创建成功',
            icon: 'success'
        })
    } catch (error) {
        Taro.showToast({
            title: error.message,
            icon: 'none'
        })
    }
}

const updateLicenseRecord = async () => {
    try {
        if (!licensePlateValue.value) {
            Taro.showToast({
                title: '请补充车牌',
                icon: 'none'
            })
            return
        }
        if (!dateTimeShowValue.value) {
            Taro.showToast({
                title: '请补充时间',
                icon: 'none'
            })
            return
        }
        // if (!phoneNumberValue.value) {
        //     Taro.showToast({
        //         title: '请补充联系方式',
        //         icon: 'none'
        //     })
        //     return
        // }
        const { result } = await licenseRecordUpdate({
            license: licensePlateValue.value,
            time: dateTimeShowValue.value,
            phoneNumber: phoneNumberValue.value
        })
        console.log('result', result)

        Taro.showToast({
            title: '保存成功',
            icon: 'success'
        })

        Taro.navigateBack()
    } catch (error) {
        Taro.showToast({
            title: error.message,
            icon: 'none'
        })
    }
}

// 查询信息
const queryLicenseInfo = ref<ILicenseRecord | null>(null)
const queryLicenseRecord = async () => {
    try {
        if (!licensePlateValue.value) {
            Taro.showToast({
                title: '请补充车牌',
                icon: 'none'
            })
            return
        }
        const { result } = await licenseRecordQuery({
            license: licensePlateValue.value
        })
        queryLicenseInfo.value = result || ''
    } catch (error) {
        Taro.showToast({
            title: error.message,
            icon: 'none'
        })
        queryLicenseInfo.value = null
    }
}

// 复制联系电话
const copyPhoneNumber = () => {
    Taro.setClipboardData({
        data: phoneNumberValue.value
    })
}

// 按钮点击前置处理
const hanldeBtnClick = (type: string) => {
    if (!isLogin.value) {
        toLogin()
        return
    }
    // if (!isAgreeValue.value) {
    //     Taro.showToast({
    //         title: '请确认勾选用户协议和隐私协议',
    //         icon: 'none'
    //     })
    //     return
    // }
    switch (type) {
        case 'create':
            createLicenseRecord()
            break
        case 'update':
            updateLicenseRecord()
            break
        case 'query':
            queryLicenseRecord()
            break
    }
}

// 编辑车牌
const handleEditType = async () => {
    Taro.setNavigationBarTitle({
        title: '编辑我的车辆信息'
    })

    const { result } = await licenseRecordQuery({
        license: license
    })
    licensePlateValue.value = result.license
    dateTimeShowValue.value = result.time
    phoneNumberValue.value = result.phoneNumber
}

onMounted(() => {
    switch (pageType) {
        case 'edit':
            handleEditType()
            break

        default:
            break
    }
})
</script>

<style lang="less">
.nut-input {
    padding: 0;
}
.nut-checkbox {
    margin-right: 0;
}
</style>
